package com.fun.java8;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 流操作示例
 * 1.JDK8中有双冒号的用法，就是把方法当做参数传到stream内部，使stream的每个元素都传入到该方法里面执行一下
 */
public class StreamTests {
    private List<Person> personList=new ArrayList<>();

    public List<Person> getPersonList() {
        return personList;
    }

    public void setPersonList(List<Person> personList) {
        this.personList = personList;
    }

    /**
     * 初始化数据
     */
    public void init() {
        Person person1=new Person("1","A",19);
        Person person2=new Person("1","B",11);
        Person person3=new Person("1","B",10);
        Person person4=new Person("1","A",28);
        personList.add(person1);
        personList.add(person2);
        personList.add(person3);
        personList.add(person4);
    }
    public static void main(String[] args){
          StreamTests streamTests=new StreamTests();
          streamTests.init();
          streamTests.listToMapList(streamTests.getPersonList());
          streamTests.groupCount(streamTests.getPersonList());
    }

    /**
     * 根据某个属性分组
     */
    public  void listToMapList(List<Person> personList){
        Map<String,List<Person>> personListMap=!personList.isEmpty()
                ? personList.stream().collect(Collectors.groupingBy(Person::getName))
                : new HashMap<>();
        System.out.println(personListMap);
    }

    /**
     * 分组计数
     */
    public void groupCount(List<Person> personList){
        Map<String,Long> personCount=!personList.isEmpty()
                ? personList.stream().collect(Collectors.groupingBy(Person::getName,Collectors.counting()))
                : new HashMap<>();
        System.out.println(personCount);
    }
}
